<template>
  <div class="post-create">
    <h2>发布文章</h2>
    <el-form :model="post" ref="postForm" label-width="120px">
      <el-form-item label="标题">
        <el-input v-model="post.title" placeholder="请输入文章标题" />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="post.category_id" placeholder="请选择分类">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="post.tags" placeholder="请输入标签，用逗号隔开" />
      </el-form-item>
      <el-form-item label="内容">
        <QuillEditor v-model:content="post.content" theme="snow" />
        <el-input type="textarea" v-model="post.content" placeholder="请输入文章内容" rows="6" />
      </el-form-item>
      <el-form-item label="封面图片上传">
        <el-upload
          class="upload-demo"
          ref="uploadRef"
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="handleAttachmentSuccess"
          :on-error="handleAttachmentError"
          :on-progress="handleUploadProgress"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <el-button type="primary" icon="el-icon-upload">封面图片上传</el-button>
        </el-upload>

        <transition name="fade">
          <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" status="success" />
        </transition>

        <div v-if="post.attachments.length > 0" class="attachment-list">
          <ul>
            <li v-for="(file, index) in post.attachments" :key="index" class="attachment-item">
              <a :href="file.url" target="_blank">{{ file.name }} 点击预览大图</a>
            </li>
          </ul>
        </div>

        <!-- 图片预览区域 -->
        <div v-if="previewImage" class="image-preview">
          <img :src="previewImage" alt="图片预览" class="preview-image" />
        </div>
      </el-form-item>
      
    <el-form-item label="多附件上传">
      <el-upload
        class="upload-demo"
        ref="multipleUploadRef"
        :action="uploadMultipleUrl"
        :headers="uploadHeaders"
        :on-success="handleMultipleAttachmentSuccess"
        :on-error="handleAttachmentError"
        :on-progress="handleUploadProgress"
        :before-upload="beforeUpload"
        :multiple="true"
        :limit="5"
        :on-exceed="handleExceed"
        name="files" 
      >
        <el-button type="primary" icon="el-icon-upload">上传附件</el-button>
        <template #tip>
          <div class="el-upload__tip">支持上传多个文件，文件格式为 JPG, PNG 或 PDF，单个文件大小不超过 5MB</div>
        </template>
      </el-upload>

      <transition name="fade">
        <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" status="success" />
      </transition>

      <div v-if="post.multipleAttachments.length > 0" class="attachment-list">
        <ul>
          <li v-for="(file, index) in post.multipleAttachments" :key="index" class="attachment-item">
            <div class="file-info">
              <el-icon><Document /></el-icon>
              <a :href="file.url" target="_blank">{{ file.name }}</a>
            </div>
            <div class="file-actions">
              <el-button 
                type="danger" 
                circle 
                @click="removeAttachment(index)"
                class="delete-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </li>
        </ul>
      </div>
    </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitPost">发布文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { ref } from "vue";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { Document, Delete } from '@element-plus/icons-vue'

export default {
  name: "ArticleRelease",
  components: {
    Document,
    Delete
  },
  setup() {
    const post = ref({
      title: "",
      category_id: null,
      tags: "",
      content: "",
      attachments: [],
      multipleAttachments: [], // 新增多附件上传
    });

    const categories = ref([
      { id: 1, name: "Java" },
      { id: 2, name: "Python" },
      { id: 3, name: "Kotlin" },
    ]);

    const uploadUrl = "http://localhost:9090/upload";
    const uploadMultipleUrl = "http://localhost:9090/upload-multiple"; // 多附件上传接口
    const uploadHeaders = { Authorization: getToken() };
    const uploadRef = ref(null);
    const multipleUploadRef = ref(null); // 多附件上传的引用
    const uploadProgress = ref(0);
    const previewImage = ref(null);

    const handleAttachmentSuccess = (response) => {
      if (!response.url) {
        ElMessage.error("封面图片上传失败，未返回 URL");
        return;
      }
      post.value.attachments.push({ url: response.url });

      if (response.url.match(/\.(jpeg|jpg|png|gif)$/i)) {
        previewImage.value = response.url;
      }

      uploadProgress.value = 100;
      setTimeout(() => {
        uploadProgress.value = 0;
      }, 1500);
    };

    const handleMultipleAttachmentSuccess = (response) => {
      if (!response.urls || response.urls.length === 0) {
        ElMessage.error("附件上传失败，未返回 URL");
        return;
      }
      response.urls.forEach((url) => {
        post.value.multipleAttachments.push({ url });
      });

      uploadProgress.value = 100;
      setTimeout(() => {
        uploadProgress.value = 0;
      }, 1500);
    };

    const handleAttachmentError = (error) => {
      console.error("文件上传失败", error);
      ElMessage.error("文件上传失败，请重试");
      uploadProgress.value = 0;
    };

    const handleUploadProgress = (event) => {
      uploadProgress.value = Math.round((event.loaded / event.total) * 100);
    };

    const beforeUpload = (file) => {
      const allowedTypes = ["image/jpeg", "image/png", "application/pdf"];
      const maxFileSize = 5;
      if (!allowedTypes.includes(file.type)) {
        ElMessage.warning("仅支持 JPG, PNG 或 PDF 格式的文件");
        return false;
      }
      if (file.size / 1024 / 1024 > maxFileSize) {
        ElMessage.warning(`文件大小不能超过 ${maxFileSize} MB`);
        return false;
      }
      uploadProgress.value = 0;
      return true;
    };

    const handleExceed = () => {
      ElMessage.warning("最多只能上传 5 个文件");
    };

    const removeAttachment = async (index) => {
      try {
        const attachment = post.value.multipleAttachments[index];
        const token = getToken();
        
        // 显示确认对话框
        await ElMessageBox.confirm(
          '确定要删除这个附件吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );
        
        // 从URL中提取文件名
        const filename = attachment.url.split('/').pop();
        
        // 调用后端删除API
        await axios.delete(`http://localhost:9090/delete-attachment/${filename}`, {
          headers: { Authorization: token }
        });
        
        // 删除成功后从数组中移除
        post.value.multipleAttachments.splice(index, 1);
        ElMessage.success('附件删除成功');
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除附件失败', error);
          ElMessage.error('删除附件失败，请重试');
        }
      }
    };

    const submitPost = async () => {
      const token = getToken();
      if (!token) {
        ElMessage.warning("请先登录！");
        return;
      }

      const postData = {
        title: post.value.title,
        category_id: post.value.category_id,
        tags: post.value.tags,
        content: post.value.content,
        attachment_url: post.value.attachments.map(a => a.url).join(','),
        multiple_attachments: post.value.multipleAttachments.map(a => a.url).join(','), // 多附件上传
      };

      try {
        const response = await axios.post(
          "http://localhost:9090/article_release",
          postData,
          { headers: { Authorization: token } }
        );
        ElMessage.success("文章发布成功");
        console.log("文章 ID:", response.data.post_id); // 打印文章 ID 用于调试
      } catch (error) {
        console.error("发布文章失败", error);
        ElMessage.error("文章发布失败，请检查网络连接或稍后重试");
      }
    };

    return {
      post,
      categories,
      uploadUrl,
      uploadMultipleUrl,
      uploadHeaders,
      handleAttachmentSuccess,
      handleMultipleAttachmentSuccess,
      handleAttachmentError,
      handleUploadProgress,
      beforeUpload,
      uploadRef,
      multipleUploadRef,
      submitPost,
      uploadProgress,
      previewImage,
      handleExceed,
      removeAttachment,
      QuillEditor,
      Document,
      Delete,
    };
  },
};
</script>
<style scoped>
.post-create {
  max-width: 800px;
  margin: 0 auto;
}
.attachment-list {
  margin-top: 20px;
}
.attachment-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.attachment-item {
  margin: 10px 0;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  transition: all 0.3s ease;
}
.attachment-item:hover {
  background-color: #e4e7ed;
}
.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}
.file-info a {
  color: #409eff;
  text-decoration: none;
  word-break: break-all;
}
.file-info a:hover {
  color: #66b1ff;
}
.file-actions {
  margin-left: 16px;
}
.delete-btn {
  padding: 6px;
  transition: all 0.3s ease;
}
.delete-btn:hover {
  transform: scale(1.1);
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
.image-preview {
  margin-top: 20px;
  text-align: center;
}
.preview-image {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>